home *** CD-ROM | disk | FTP | other *** search
/ HPAVC / HPAVC CD-ROM.iso / WINER.ZIP / EVALUATE.BAS < prev    next >
BASIC Source File  |  1992-05-13  |  1KB  |  45 lines

  1. '********** EVALUATE.BAS - simple expression evaluator
  2.  
  3. 'Copyright (c) 1992 Ethan Winer
  4.  
  5. DECLARE FUNCTION Evaluate# (Formula$)
  6.  
  7. INPUT "Enter an expression: ", Expr$
  8. PRINT "That evaluates to"; Evaluate#(Expr$)
  9.  
  10. FUNCTION Evaluate# (Formula$)
  11.  
  12.   'Search for an operator using INSTR as a
  13.   'table lookup.  If found, remember which
  14.   'one and also its position in the string.
  15.   FOR Position% = 1 TO LEN(Formula$)
  16.     Operation% = INSTR("+-*/", MID$(Formula$, Position%, 1))
  17.     IF Operation% THEN EXIT FOR
  18.   NEXT
  19.  
  20.   'Get the value of the left part, and a
  21.   'tentative value for the right portion.
  22.   LeftVal# = VAL(Formula$)
  23.   RightVal# = VAL(MID$(Formula$, Position% + 1))
  24.  
  25.   'See if there's another level to evaluate.
  26.   Paren% = INSTR(Position%, Formula$, "(")
  27.  
  28.   'If there is, call ourself for a new RightVal#.
  29.   IF Paren% THEN RightVal# = Evaluate#(MID$(Formula$, Paren% + 1))
  30.  
  31.   'No more to evaluate.  Perform the appropriate
  32.   'operation and exit.
  33.   SELECT CASE Operation%
  34.     CASE 1
  35.       Evaluate# = LeftVal# + RightVal#
  36.     CASE 2
  37.       Evaluate# = LeftVal# - RightVal#
  38.     CASE 3
  39.       Evaluate# = LeftVal# * RightVal#
  40.     CASE 4
  41.       Evaluate# = LeftVal# / RightVal#
  42.   END SELECT
  43.  
  44. END FUNCTION
  45.